import os, sys, ctypes, posix_ipc, fcntl, time, mmap, traceback
from threading import Thread
from mmap_proxy import VideoMMapProxy
from multiprocessing import Queue

lib_video = ctypes.cdll.LoadLibrary("./libHiApp.so")

__video_flag = 17256

def get_video_flag():
    global __video_flag
    __video_flag += 1
    if __video_flag > 10000000:
        __video_flag = 17256
    return __video_flag

SHARE_PATH_PRE_FIX = "/tmp/hi/video_test_"

class VideoProxy():
    def __init__(self):
        self.__video_flag = get_video_flag()
        self.__share_path = SHARE_PATH_PRE_FIX + str(self.__video_flag) + "_bgr"
        self.__on_image = None
        self.__mmap_proxy = VideoMMapProxy()
        self.__shape =  None
        self.__is_exit = True
        self.__receive_thread = None
        self.__id = -1        

    def start(self, video_url, port, width, height, video_id, on_image):
        self.__input_video_id = video_id
        self.__on_image = on_image
        self.__shape = (width, height, 3)
        rtsp = bytes(video_url,"utf8")
        self.__remove_share_file()
        self.__id = lib_video.hi_video_image_share_start(rtsp, port, width, height, self.__video_flag)
        print("call hi_video_image_share_start, result:", self.__id)
        self.__start_receive_thread()

    def stop(self):
        lib_video.hi_video_image_share_stop(id)
        if self.__receive_thread:
            self.__is_exit = True
            self.__receive_thread.join()
            self.__receive_thread = None

    def __remove_share_file(self):        
        os.system('rm ' + SHARE_PATH_PRE_FIX + str(self.__video_flag) + "*")

    def __start_receive_thread(self):
        print("__share_path:", self.__share_path)
        while not os.path.exists(self.__share_path):
            time.sleep(0.3)
        self.__receive_thread = Thread(target=VideoProxy.on_receive_thread, args=(self,))
        self.__receive_thread.start()
        
    def on_receive_thread(self):
        print("on_receive_thread begin")
        self.__is_exit = False
        while not os.path.exists(self.__share_path):
            time.sleep(0.3)
        self.__mmap_proxy.init(self.__share_path)
        try:
            with open(self.__share_path, "r+b") as f:
                mm = mmap.mmap(f.fileno(), 0)
                while self.__is_exit != True:
                    img = self.__mmap_proxy.read(mm, f, self.__shape)
                    if not img is None:                    
                        self.__on_image(self.__input_video_id, img)
        except Exception as e:
            print('receive pic exception:' + str(e))   
            exc_type, exc_value, exc_obj = sys.exc_info()
            traceback.print_tb(exc_obj)
        print('pic recevie quit')    
        self.__mmap_proxy.release()

    @staticmethod
    def release():
        VideoMMapProxy.relase_proxy()
